from django.shortcuts import render
from django.db import connection
from predict import cf,iupred
from django.http import FileResponse,Http404


def index(request):
    return render(request, 'index.html')

class PageInfo(object):
    def __init__(self,current_page,all_count,per_page,show_page=7):
        try:
            self.current_page=int(current_page)
        except Exception as e:
            self.current_page=1
        self.per_page=per_page
        a,b=divmod(all_count,per_page)
        if b:
            a=a+1
        self.all_page=a
        self.show_page=show_page
    def start(self):
        return (self.current_page-1)*self.per_page
    def end(self):
        return self.current_page*self.per_page

    @property
    def page(self):
        # v="<a href='/browse?page=1'>1</a>"
        # return  v
        page_list=[]
        half=int((self.show_page-1)/2)
        if self.all_page<self.show_page:
            begin=1
            stop=self.all_page+1
        else:
            if self.current_page<half:
                begin=1
                stop=self.show_page+1
            else:
                if self.current_page+half>self.all_page:
                    begin=self.all_page-self.show_page+1
                    stop=self.all_page+1
                else:
                    begin=self.current_page-half
                    stop=self.current_page+half+1
        # begin=self.current_page-5
        # stop=self.current_page+half+1
        shou="<li><a href='/browse?page=%s' >首页</a></li>"%(1)
        page_list.append(shou)
        if self.current_page<=1:
            pre = "<li><a href='# '>上一页</a></li>"
        else:
            pre="<li><a href='/browse?page=%s'>上一页</a></li>"%(self.current_page-1)
        page_list.append(pre)
        for i in range(begin,stop):
            temp="<li><a href='/browse?page=%s'>%s</a></li>"%(i,i)
            page_list.append(temp)
        if self.current_page >= self.all_page:
            nex = "<li><a href='# '>下一页</a></li>"
        else:
            nex = "<li><a href='/browse?page=%s'>下一页</a></li>" % (self.current_page +1)
        page_list.append(nex)
        wei="<li><a href='/browse?page=%s' >尾页</a></li>"%(self.all_page)
        page_list.append(wei)
        return ''.join(page_list)


def browse(request):
    cursor = connection.cursor()
    all_count =388175
    current_page = request.GET.get('page')
    page_info = PageInfo(current_page, all_count, 15)
    cursor.execute("select * from en where id between '%d' and '%d'"%(page_info.start(),page_info.end()))
    out_list=cursor.fetchall()
    return render(request,'browse.html',{'out_list':out_list,'page_info':page_info})

def detail(request, PPCsPG):
    cursor=connection.cursor()
    cursor.execute("select * from en where PPCsPG='%s'"%PPCsPG)
    rows=cursor.fetchall()
    # rows=row[10]
    for row in rows:
        pass
    strc=cf.ChouFasman(row[10])
    domain=iupred.domain(row[10])
    return render(request, 'detail.html', context={'test': row,'strc':strc,'domain':domain})


def search(request):
    return  render(request,'search.html')

def result(request):
    cursor = connection.cursor()
    specie = request.GET.get('specie')
    # print(specie)
    # condition1=Q(species__icontains=specie)


    # condition2=Q(type__icontains=type)
    # length = request.GET.get('length')
    # if length=='all':
    #     start = 0
    #     end = 330
    # else:
    #         start = float(length.split('~')[0])
    #         end = float(length.split('~')[1])
    # condition3=Q(len__range=(start,end))
    st=request.GET.get('start')
    ed=request.GET.get('end')
    bg=request.GET.get('begin')
    so=request.GET.get('stop')
    # GC = request.GET.get('GC')
    # if GC=='all':
    #     started=0
    #     ended=99
    # else:
    #     started=float(GC.split('~')[0])
    #     ended=float(GC.split('~')[1])
    # condition4=Q(gc_field__range=(started,ended))
    # data = Out.objects.filter(condition1,condition2,condition3,condition4)
    type = request.GET.get('type')
    data=''
    if specie:
        if type == 'all':
            cursor.execute("select * from en where  Species like '%s'and Len between '%s' and '%s' and GC between '%s' and '%s'" % ('%'+specie+'%',st, ed, bg, so))
            # cursor.execute("select * from en where Species like '%s' and Len between '%s' and '%s'"%('%'+specie+'%',st,ed))
        else:
            cursor.execute("select * from en where Species like '%s' and Type = '%s' and Len between '%s' and '%s' and GC between '%s' and '%s'"%('%'+specie+'%',type,st,ed,bg,so))
            # cursor.execute("select * from en where like '%s' and Type='&s' and Len between '%s' and '%s'"%('%'+specie+'%',type,st,ed))
        data = cursor.fetchall()
    else :
        data=''
    # if specie:
    #     cursor.execute("select * from en where Species like '%s'"%('%'+specie+'%'))
    #     data = cursor.fetchall()
    # else:
    #     data=''
    # data=cursor.fetchall()

    return render( request, 'result.html', {'data': data })

def download(request):
    return  render(request,'download.html')


def DLcsv(request):
    try:
        file=open('wen/static/file/sORFs.txt','rb')
        response=FileResponse(file)
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="sorfs.txt"'
        return response
    except Exception:
        raise Http404('Download error')
def genetic(request):
    return render(request,'genetic_code.html',{})

def help(request):
    return render(request,'help.html')

